package com.governtalk.backend.service.impl;

import com.governtalk.backend.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${file.upload.path:uploads/}")
    private String uploadPath;

    @Value("${file.upload.url:http://localhost:8080/uploads/}")
    private String uploadUrl;

    @Override
    public String uploadImage(MultipartFile file) {
        System.out.println("=== 开始文件上传 ===");
        System.out.println("原始文件名: " + file.getOriginalFilename());
        System.out.println("文件大小: " + file.getSize() + " 字节");
        System.out.println("文件类型: " + file.getContentType());
        System.out.println("是否为空: " + file.isEmpty());
        
        if (file.isEmpty()) {
            throw new RuntimeException("上传的文件为空");
        }
        
        try {
            // 确保上传目录存在
            Path uploadDir = Paths.get(uploadPath);
            if (!Files.exists(uploadDir)) {
                System.out.println("创建上传目录: " + uploadDir.toAbsolutePath());
                Files.createDirectories(uploadDir);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = ".jpg"; // 默认扩展名
            
            // 优先根据内容类型确定扩展名
            if (file.getContentType() != null) {
                if (file.getContentType().startsWith("image/png")) {
                    extension = ".png";
                } else if (file.getContentType().startsWith("image/gif")) {
                    extension = ".gif";
                } else if (file.getContentType().startsWith("image/webp")) {
                    extension = ".webp";
                } else if (file.getContentType().startsWith("image/jpeg") || file.getContentType().startsWith("image/jpg")) {
                    extension = ".jpg";
                }
            } else if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString() + extension;
            System.out.println("生成的文件名: " + fileName);

            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            System.out.println("文件保存路径: " + filePath.toAbsolutePath());
            
            // 使用try-with-resources确保流正确关闭
            try (java.io.InputStream inputStream = file.getInputStream()) {
                Files.copy(inputStream, filePath);
            }
            
            // 验证文件是否成功保存
            if (Files.exists(filePath) && Files.size(filePath) > 0) {
                System.out.println("✅ 文件上传成功: " + fileName);
                System.out.println("✅ 文件大小: " + Files.size(filePath) + " 字节");
                System.out.println("✅ 文件类型: " + file.getContentType());
                return fileName;
            } else {
                throw new RuntimeException("文件保存失败，文件不存在或为空");
            }
            
        } catch (IOException e) {
            System.err.println("❌ 文件上传失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        } catch (Exception e) {
            System.err.println("❌ 文件上传异常: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("文件上传异常: " + e.getMessage(), e);
        }
    }

    @Override
    public String getImageUrl(String fileName) {
        return uploadUrl + fileName;
    }

    @Override
    public boolean deleteImage(String fileName) {
        try {
            System.out.println("=== 开始删除文件 ===");
            System.out.println("文件名: " + fileName);
            
            Path filePath = Paths.get(uploadPath, fileName);
            System.out.println("文件路径: " + filePath.toAbsolutePath());
            
            if (Files.exists(filePath)) {
                boolean deleted = Files.deleteIfExists(filePath);
                if (deleted) {
                    System.out.println("✅ 文件删除成功: " + fileName);
                } else {
                    System.out.println("⚠️ 文件删除失败: " + fileName);
                }
                return deleted;
            } else {
                System.out.println("⚠️ 文件不存在: " + fileName);
                return true; // 文件不存在也算删除成功
            }
        } catch (IOException e) {
            System.err.println("❌ 删除文件失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 清理临时文件
     */
    public void cleanupTempFiles() {
        try {
            System.out.println("=== 开始清理临时文件 ===");
            Path tempDir = Paths.get("temp");
            if (Files.exists(tempDir)) {
                Files.walk(tempDir)
                    .filter(Files::isRegularFile)
                    .forEach(file -> {
                        try {
                            Files.delete(file);
                            System.out.println("✅ 删除临时文件: " + file.getFileName());
                        } catch (IOException e) {
                            System.err.println("❌ 删除临时文件失败: " + file.getFileName() + ", 错误: " + e.getMessage());
                        }
                    });
                System.out.println("✅ 临时文件清理完成");
            } else {
                System.out.println("ℹ️ 临时目录不存在，无需清理");
            }
        } catch (IOException e) {
            System.err.println("❌ 清理临时文件失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}